'use strict';
const BaseService = require('./base');
const rp = require('request-promise');
const StringUtil = require('../utils/StringUtil');
const Constant = require('../config/Constant');
const OperatorType = require('../config/OperatorType');
const ResponseUtil = require('../utils/ResponseUtil');
const RCEM = require('../utils/ResultCodeEnumMsg');


class WechatService extends BaseService {

    constructor(ctx) {
        super(ctx);

        this.accessTokenRedis = {
            key: 'wechattoken:course',
            exp: 7140//提前一分钟结束
        };


        this.WECHAT_CONFIG = {
            APPID: 'wxfa9ce2f316f9a8eb',
            APPSECRET: '4562dafee13d9b951296a0b68a3c4209'
        }
    }


    getWechatConfig() {
        return this.WECHAT_CONFIG;
    }


    async getAccessToken(code){
        let redAccessToken = await this.ctx.service.redis.get(this.accessTokenRedis.key);
        if (redAccessToken) {
            return redAccessToken;
        }

        let res = await rp({
            method: "GET",
            uri: `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${this.WECHAT_CONFIG.APPID}&secret=${this.WECHAT_CONFIG.APPSECRET}&code=${code}&grant_type=authorization_code`,
            json: true
        });

        if (res.access_token) {
            let accessToken = res.access_token;
            await this.ctx.service.redis.set(this.accessTokenRedis.key, accessToken, this.accessTokenRedis.expires_in);
            return accessToken;
        } else {
            console.error('wechat getAccessToken error', res);
            this.ctx.app.logger.error('wechat getAccessToken error', res);
            return '';
        }
    }

    async getSnsUserInfo(code){
        let accessToken = await this.getAccessToken(code);
        if(!accessToken){
            return "";
        }
        let res = await rp({
            method: "GET",
            uri: `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${this.WECHAT_CONFIG.APPID}&lang=zh_CN`,
            json: true
        });
        console.log('getSnsUserInfo result:', res);
        if (res.openid) {
            return res;
        } else {
            console.error('wechat getSnsUserInfo error', res);
            this.ctx.app.logger.error('wechat getSnsUserInfo error', res);
            return null;
        }
    }

    async oauth2Authorize(code,state){
        let snsUserInfo = await this.getSnsUserInfo(code);
        if(!snsUserInfo){
            return {token:'',error:'微信授权失败，请稍后再试'};
        }
        let userRet = this.ctx.service.user.insertUser(snsUserInfo);
        if(!userRet){
            return {token:'',error:'用户数据插入异常'};
        }

        if(userRet.status != 0){
            return {token: '', error: '账户已禁用，请联系管理员。'}
        }

        let userToken = this.ctx.service.user.__createToken(userRet.userId);
        return {token:userToken,error:'ok'};
    }

}

module.exports = WechatService;
